package com.sx.micowell.module.course.video

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.CacheDiskUtils
import com.bumptech.glide.Glide
import com.danikula.videocache.Cache
import com.dou361.ijkplayer.widget.PlayStateParams
import com.dou361.ijkplayer.widget.PlayerView
import com.example.mvvm.base.ContainerActivity
import com.example.mvvm.base.cache.CacheUtils
import com.example.mvvm.base.data.DataBindingConfig
import com.example.mvvm.until.SPUtils
import com.gyf.immersionbar.ImmersionBar
import com.miloyu.modelnet.cache.CacheBean
import com.miloyu.modelnet.cache.CacheManager
import com.miloyu.modelnet.cache.putCache
import com.miloyu.modelnet.response.CourseDetailList
import com.miloyu.modelnet.response.CourseVideoVO
import com.miloyu.modelnet.response.UserInfoVO
import com.miloyu.modelnet.response.getUrl
import com.sx.micowell.R
import com.sx.micowell.databinding.FragCourseVideoBinding
import com.sx.micowell.framework.app.*
import com.sx.micowell.framework.arouth.RouteManager
import com.sx.micowell.framework.arouth.RoutePath
import com.sx.micowell.framework.model.RecommendCourseModel

/**
 * @Author: YY
 * @Time: 2021/9/6
 * @Describe 课程视频
 */
@Route(path = RoutePath.COURSE_VIDEO)
class CourseVideoFragment : MyFragment<FragCourseVideoBinding, ContainerActivity>() {

    private var player: PlayerView? = null

    @Autowired(name = IntentKey.KEY)
    lateinit var id: String
    
    var isJumpVip: Boolean = false

    var courseVideoData: CourseVideoVO? = null

    lateinit var viewModel: RecommendCourseModel

    private var courseActionListAdapter : CourseActionListAdapter? = null

    override fun initViewModel() {
        viewModel = getFragmentScopeViewModel(RecommendCourseModel::class.java)
    }

    override fun getDataBindingConfig(): DataBindingConfig {
        return DataBindingConfig(R.layout.frag_course_video)
    }

    override fun initView() {
        // 设置状态栏字体颜色
        ImmersionBar.with(this).statusBarDarkFont(true)
            .fitsSystemWindows(false).init()

        binding.cbCollect.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) {
                viewModel.addCollection(id)
            } else {
                viewModel.cancelCollection(id)
            }
        }

        binding.tvStartTrain.setOnClickListener {
            if (isJumpVip) {
                val userInfo: UserInfoVO = CacheDiskUtils.getInstance()
                    .getSerializable(AppConstant.CacheKey.CACHE_USER_INFO) as UserInfoVO
                val bundle = Bundle()
                bundle.putSerializable(IntentKey.DATA, userInfo)
                startContainerActivity(
                    userInfo.let { RouteManager.getInstance().getMemberFragment(it).javaClass.canonicalName },
                    bundle
                )
            } else {
                if (courseVideoData != null) {
                    val bundle = Bundle()
                    bundle.putSerializable(IntentKey.DATA, courseVideoData)
                    startContainerActivity(
                        RouteManager.getInstance().getFragCourseCountDownFragment(courseVideoData!!).javaClass.canonicalName,
                        bundle
                    )
                }
            }
        }
    }

    override fun initData() {
        initPlayer()
        viewModel.getCourseVideo(id)
    }

    override fun initViewObservable() {
        super.initViewObservable()
        setCourseVideoList()

        viewModel.collectionEvent.observe(this, {
            binding.cbCollect.text = if (it) "已收藏" else "收藏课程"
        })
    }

    @SuppressLint("SetTextI18n")
    fun setCourseVideoList() {
        //取消recyclerview单独的滑动效果
        binding.recyclerAction.isNestedScrollingEnabled = false
        //设置布局管理器
        binding.recyclerAction.layoutManager = LinearLayoutManager(context)

        viewModel.courseVideoData.observe(this, {
            courseVideoData = it
            binding.tvSpecs.text = "${it.curriculum.duration}分钟  " +
                    "${it.curriculum.calorie}千卡  ${it.curriculum.basicConditions}"
            binding.tvPartake.text = "${it.curriculum.customerCount}人已参加"
            binding.tvContent.text = it.curriculum.curriculumContent
            binding.cbCollect.isChecked = it.isCollection
            if (it.curriculum.isVip == "N") {
                isJumpVip = false
                binding.tvStartTrain.text = "开始训练"
            } else {
                if (SPUtils.getInstance().getBoolean(SPKey.SP_VIP)) {
                    binding.tvStartTrain.text = "已是会员，开始训练"
                    isJumpVip = false
                } else {
                    binding.tvStartTrain.background = resources.getDrawable(R.drawable.shape_textview_bg2)
                    binding.tvStartTrain.text = "成为会员，立刻开练"
                    isJumpVip = true
                }
            }
            if (it.isCollection) {
                binding.cbCollect.text = "已收藏"
            } else {
                binding.cbCollect.text = "收藏课程"
            }

            if (it.detail.isNotEmpty()) {
                binding.tvTitle.text = it.detail[0].title
                // 播放视频
                startPlay(it.detail[0].url.getUrl(), it.detail[0].cover.getUrl())
            }

            courseActionListAdapter = CourseActionListAdapter()
            courseActionListAdapter?.data = it.detail as MutableList<CourseDetailList>
            binding.recyclerAction.adapter = courseActionListAdapter

            courseActionListAdapter?.setOnItemClickListener {adapter, view, position ->
                val courseDetailList: CourseDetailList = adapter.data[position] as CourseDetailList
                binding.tvTitle.text = courseDetailList.title
                // 播放视频
                startPlay(courseDetailList.url.getUrl(), courseDetailList.cover.getUrl())
            }
        })
    }

    /**初始化播放视频*/
    fun initPlayer(){
        player = PlayerView(activity)
            .setScaleType(PlayStateParams.fitparent)
            .forbidTouch(false)
            .hideHideTopBar(false)
            .hideSteam(true)
            .hideFullscreen(false)
            .hideRotation(true)
            .hideBottonBar(false)

    }

    /**开始播放视频*/
    fun startPlay(mp4: String, bg: String){
        context?.let {
            viewModel.currentMp4= MyApplication.instance().getProxy(it)?.getProxyUrl(mp4).toString()
            viewModel.currentURL= bg
            player!!.showThumbnail { ivThumbnail ->
                Glide.with(it)
                    .load(viewModel.currentURL)
                    .placeholder(R.color.black)
                    .error(R.color.black)
                    .into(ivThumbnail)
            }.setPlaySource(viewModel.currentMp4)
                .startPlay()
        }
        player!!.setFullListener {
            RouteManager.getInstance().intentMkVideoVideo(mp4, bg)
        }
    }

    override fun onPause() {
        super.onPause()
        player!!.pausePlay()
    }
}